package com.nbb.rpcfilter;

import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kevin_zhang on 17/01/2017.
 */
public class CommFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(CommFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

        String logId = RpcContext.getContext().getAttachment("logId");
        String itf = invocation.getAttachment("interface");
        String key;
        if (StringUtils.isNotBlank(itf))
            key = itf + ":" + invocation.getMethodName();
        else
            key = invocation.getInvoker().getUrl().getPath() + ":" + invocation.getMethodName();
        long t1 = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long t2 = System.currentTimeMillis();
        long spentMs = t2-t1;
        if (spentMs > 300 && spentMs < 2000) {
            logger.warn("{} execution time more than {} ms , {} ms has spended", new Object[]{key, 300, spentMs});
        }else if(spentMs >  2000){
            logger.error("{} execution time more than {} ms , {} ms has spended", new Object[]{key, 300, spentMs});
        }
        Map logMap = new HashMap();
        logMap.put("q_req_id", logId);
        logMap.put("q_function", key);
        logMap.put("q_opt_ip", RpcContext.getContext().getLocalAddressString());
        logMap.put("q_opt_time", beginTime);
        logMap.put("q_opt_duration", spentMs);
        logMap.put("q_req_param", invocation.getArguments());
        logMap.put("q_opt_result", result);
        logger.info(JSON.toJSONString(logMap));

        return result;
    }
}
